package MyFragment;

import static com.qb.devtest.MainActivity.mActivity;

import static Printer.UsbPrinter.ACTION_USB_PERMISSION;

import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.caysn.autoreplyprint.AutoReplyPrint;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.qb.devtest.MyApplication;
import com.qb.devtest.R;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import Printer.CaysnPrinter;
import Printer.UsbPrinter;
import utils.MyUtil;
import Printer.NetPrinter;
import Printer.PrinterCMD;

public class FragmentPrinter extends Fragment {
    Context ctx = MyApplication.getInstance();
    RadioGroup rgPrinter;
    LinearLayout llPrinterUsb,getLlPrinterNet;

    Button printerOpen,printerClose,printerPrint,printerCutter,printerCashbox;
    String currentPrinter = "USB_PRINTER", printerInfoStr = "";
    TextView printerInfo;
    Dialog loading;
    EditText printerMsg;

    UsbPrinter usbPrinter;
    CaysnPrinter caysnPrinter;
    Boolean printerIsCaysn;
    Spinner spinnerPrinterUsb;
    NetPrinter netPrinter;
    EditText netPrinterIp,netPrinterPort;

    ImageView barcodeImageView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_printer, container, false);
        rgPrinter = view.findViewById(R.id.rg_printer);
        llPrinterUsb = view.findViewById(R.id.ll_printer_usb);
        getLlPrinterNet = view.findViewById(R.id.ll_printer_net);
        rgPrinter.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                updateBtnStatus(0);
                printerInfoStr = "";
                printerInfo.setText(printerInfoStr);
                RadioButton rb  = view.findViewById(radioGroup.getCheckedRadioButtonId());
                if (rb.getText().equals("USB打印机")) {
                    llPrinterUsb.setVisibility(View.VISIBLE);
                    getLlPrinterNet.setVisibility(View.GONE);
                    currentPrinter = "USB_PRINTER";
                } else if (rb.getText().equals("网口打印机")) {
                    llPrinterUsb.setVisibility(View.GONE);
                    getLlPrinterNet.setVisibility(View.VISIBLE);
                    currentPrinter = "NET_PRINTER";
                }
            }
        });

        printerMsg = view.findViewById(R.id.printer_msg);
        String s = "零壹贰叁肆伍陆柒捌玖拾佰仟\r\n"
                +"1234567890\r\n"
                +"abcdefghijklmnopqrstuvwxyz\r\n"
                +"ABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n";
//                +"ΑΒΓΔΕΖΗΘΙΚ∧ΜΝΞΟ∏Ρ∑ΤΥΦΧΨΩ\r\n"
//                +"αβγδεζηθικλμνξοπρστυφχψω\r\n"
//                +"你好，欢迎使用！\r\n"
//                +"你號，歡迎使用！\r\n"
//                +"こんにちは、ようこそ！\r\n"
//                +"안녕하세요, 어서 오세요！\r\n";
        printerMsg.setText(s);
        printerInfo = view.findViewById(R.id.printer_info);
        printerInfo.setText("");
        printerInfoStr = "";

        spinnerPrinterUsb = view.findViewById(R.id.spinner_printer_usb);
        usbPrinterInit();

        netPrinterIp = view.findViewById(R.id.net_printer_ip);
        netPrinterIp.setText("192.168.6.100");
        netPrinterPort = view.findViewById(R.id.net_printer_port);
        netPrinterPort.setText("9100");
        netPrinterThreadStart();

        printerOpen = view.findViewById(R.id.printer_open);
        printerClose = view.findViewById(R.id.printer_close);
        printerPrint = view.findViewById(R.id.printer_print);
        printerCutter = view.findViewById(R.id.printer_cutter);
        printerCashbox = view.findViewById(R.id.printer_cashbox);
        printerOpen.setOnClickListener(view1 -> {
            if (currentPrinter.equals("USB_PRINTER")) {
                usbPrinterCommand(1);
            } else if (currentPrinter.equals("NET_PRINTER")) {
                netPrinterHandler.sendEmptyMessage(1);
            }
        });
        printerClose.setOnClickListener(view1 -> {
            if (currentPrinter.equals("USB_PRINTER")) {
                usbPrinterCommand(5);
            } else if (currentPrinter.equals("NET_PRINTER")) {
                netPrinterHandler.sendEmptyMessage(5);
            }
        });
        printerPrint.setOnClickListener(view1 -> {
            if (currentPrinter.equals("USB_PRINTER")) {
                usbPrinterCommand(2);
            } else if (currentPrinter.equals("NET_PRINTER")) {
                netPrinterHandler.sendEmptyMessage(2);
            }
        });
        printerCutter.setOnClickListener(view1 -> {
            if (currentPrinter.equals("USB_PRINTER")) {
                usbPrinterCommand(3);
            } else if (currentPrinter.equals("NET_PRINTER")) {
                netPrinterHandler.sendEmptyMessage(3);
            }
        });
        printerCashbox.setOnClickListener(view1 -> {
            if (currentPrinter.equals("USB_PRINTER")) {
                usbPrinterCommand(4);
            } else if (currentPrinter.equals("NET_PRINTER")) {
                netPrinterHandler.sendEmptyMessage(4);
            }
        });

        updateBtnStatus(0);

        barcodeImageView = view.findViewById(R.id.barcode_image);
//        createBarCode();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 在这里初始化你的Fragment视图组件
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mActivity.unregisterReceiver(usbPrinter.usbReceiver);
        if (netPrinterThread != null) netPrinterThread.interrupt();
    }

    /**************************************************
     ********** usb打印机***
     *************************************************/

    private void usbPrinterInit() {
        printerIsCaysn = false;
        usbPrinter = new UsbPrinter();
        caysnPrinter = new CaysnPrinter();
        usbPrinter.usbManager = (UsbManager) mActivity.getSystemService(Context.USB_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            usbPrinter.permissionIntent = PendingIntent.getBroadcast(mActivity, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE);
        } else {
            usbPrinter.permissionIntent = PendingIntent.getBroadcast(mActivity, 0, new Intent(ACTION_USB_PERMISSION), 0);
        }
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        mActivity.registerReceiver(usbPrinter.usbReceiver, filter);
        usbPrinter.enumeraterDevices(ctx,spinnerPrinterUsb);
        spinnerPrinterUsb.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                // Toast.makeText(mContext, "你点击的是:"+ spinner_device_list.get(pos), Toast.LENGTH_SHORT).show();
                usbPrinterCommand(5);
                printerInfoStr = "";
                usbPrinter.myUsbDevice = usbPrinter.usb_device.get(pos);
                usbPrinter.usbManager.requestPermission(usbPrinter.myUsbDevice, usbPrinter.permissionIntent);
                printerInfoStr = printerInfoStr + "  设备类型：" + usbPrinter.myUsbDevice.getProductName();
                String pMfn = usbPrinter.myUsbDevice.getManufacturerName();
                printerInfoStr = printerInfoStr + "  设备厂商：" + pMfn + "\n";
                printerInfo.setText(printerInfoStr);
                printerIsCaysn = pMfn.equals("Caysn") || pMfn.equals("caysn");
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
    }

    private void usbPrinterCommand(int action) {
        if (action == 1) {
            String r = "";
            if (printerIsCaysn) r = caysnPrinter.OpenPort();
            else r = usbPrinter.open();
            if (r.equals("success")) {
                printerInfoStr = printerInfoStr + "\n打印机连接成功！";
            } else {
                printerInfoStr = printerInfoStr + "\n"+r;
            }
            updateUI(1,printerInfoStr);
        }
        if (action == 2 ) {
            String d = MyUtil.formatDateTime2Num(new Date(),1);
            if (printerIsCaysn) {
                caysnPrinter.PrintTest(String.valueOf(printerMsg.getText()),d);
                /*
                Bitmap bitmap = MyUtil.getImageFromAssetsFile(ctx,"RasterImage/sale.png");
                caysnPrinter.PrintImage(bitmap);
                caysnPrinter.PrinterTest58();
                 */
            } else {
                usbPrinter.PrintText("打印测试\n\n",1,3,0);
                usbPrinter.PrintText(String.valueOf(printerMsg.getText()),0,2,0);
                usbPrinter.PrintTiaoMa(d,60,30,2, 1, 2);
                usbPrinter.PageGo(1);
            }
        }
        if (action == 3 ) {
            if (printerIsCaysn) caysnPrinter.CutPage(1);
            else usbPrinter.CutPage(1);
        }
        if (action == 4 ) {
            if (printerIsCaysn) caysnPrinter.OpenCashBox();
            else usbPrinter.OpenCashBox();
        }
        if (action == 5 ) {
            String r = "";
            if (printerIsCaysn) r = caysnPrinter.ClosePort();
            else r = usbPrinter.close();
            if (r.equals("closed")) {
                printerInfoStr = printerInfoStr + "\n打印机已关闭！";
            } else {
                printerInfoStr = printerInfoStr + "\n"+r;
            }
            updateUI(0,printerInfoStr);
        }
    }

    /**************************************************
     ********** 网络打印机***
     *************************************************/
    private HandlerThread netPrinterThread = null;
    private Handler netPrinterHandler;

    // 网络打印机子线程
    private void netPrinterThreadStart() {
        netPrinter = new NetPrinter();
        String printIp = netPrinterIp.getText().toString().trim();
        int printPort = Integer.parseInt(netPrinterPort.getText().toString());
        printerInfoStr = "打印机ip："+printIp+"，打印机端口："+printPort+"\n";
        netPrinter = new NetPrinter();

        netPrinterThread = new HandlerThread("handler thread");
        netPrinterThread.start();
        netPrinterHandler = new Handler(netPrinterThread.getLooper()){
            public void handleMessage(android.os.Message msg) {
                MyUtil.showLog("当前子线程是----->", Thread.currentThread()+":"+msg.what);
                // 连接打印机
                if (msg.what==1) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loading = ProgressDialog.show(mActivity, "", "打印机连接中……", false);
                        }
                    });
                    String p = netPrinter.Open(printIp,printPort);
                    if (p.equals("success")) {
                        printerInfoStr = printerInfoStr + "\n打印机连接成功！";
                    } else {
                        printerInfoStr = printerInfoStr + "\n"+p;
                    }
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loading.dismiss();
                            printerInfo.setText(printerInfoStr);
                            updateBtnStatus(1);
                        }
                    });
                }
                // 打印
                if (msg.what==2) {
                    try {
                        netPrinter.PrintText("打印测试\n\n",1,3,0);
                        netPrinter.PrintText(String.valueOf(printerMsg.getText()),0,2,0);
                        String d = MyUtil.formatDateTime2Num(new Date(),1);
                        netPrinter.PrintTiaoMa(d,80,50,2, 1, 2);
                        netPrinter.PageGo(1);
                    } catch (Exception e) {
                        // e.printStackTrace();
                        printerInfoStr = printerInfoStr + "\n打印机连接失败："+e.getMessage();
                        updateUI(1,printerInfoStr);
                    }
                }
                // 切纸
                if (msg.what==3) {
                    try {
                        netPrinter.CutPage(1);
                    } catch (Exception e) {
                        // e.printStackTrace();
                        printerInfoStr = printerInfoStr + "\n打印机连接失败："+e.getMessage();
                        updateUI(1,printerInfoStr);
                    }
                }
                // 开钱箱
                if (msg.what==4) {
                    try {
                        netPrinter.OpenCashBox();
                    } catch (Exception e) {
                        // e.printStackTrace();
                        printerInfoStr = printerInfoStr + "\n打印机连接失败："+e.getMessage();
                        updateUI(1,printerInfoStr);
                    }
                }
                // 关闭打印机
                if (msg.what==5) {
                    try {
                        netPrinter.Close();
                        printerInfoStr = printerInfoStr + "\n打印机已关闭！";
                        updateUI(0,printerInfoStr);
                    } catch (Exception e) {
                        printerInfoStr = printerInfoStr + "\n打印机关闭失败："+e.getMessage();
                        updateUI(1,printerInfoStr);
                    }
                }
            };
        };
    }

    // 更新界面及按钮状态
    private void updateUI(int f,String msg) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateBtnStatus(f);
                printerInfo.setText(msg);
            }
        });
    }

    private void updateBtnStatus(int f) {
        if (f==0) {
            printerOpen.setEnabled(true);
            printerClose.setEnabled(false);
            printerPrint.setEnabled(false);
            printerCutter.setEnabled(false);
            printerCashbox.setEnabled(false);
        }
        if (f==1) {
            printerOpen.setEnabled(false);
            printerClose.setEnabled(true);
            printerPrint.setEnabled(true);
            printerCutter.setEnabled(true);
            printerCashbox.setEnabled(true);
        }
    }

    public void createBarCode() {
        String content = "Hello, zxing!";
        MultiFormatWriter writer = new MultiFormatWriter();

        try {
            // 创建BitMatrix对象，它表示生成的条码图像
            BitMatrix bitMatrix = null;
            bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, 800, 200);

            // 创建Bitmap对象，并将BitMatrix转换为Bitmap
            Bitmap bitmap = Bitmap.createBitmap(bitMatrix.getWidth(), bitMatrix.getHeight(), Bitmap.Config.ARGB_8888);
            for (int x = 0; x < bitMatrix.getWidth(); x++) {
                for (int y = 0; y < bitMatrix.getHeight(); y++) {
                    bitmap.setPixel(x, y, bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE);
                }
            }

            // 显示生成的条码图像
            barcodeImageView.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

}